package com.object.module.lq.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.object.aop.transaction.LqTransaction;
import com.object.dao.sys.TRoleDao;
import com.object.module.lq.sys.service.TRoleAuthorizationService;
import com.object.module.lq.sys.service.TRolePermissionService;
import com.object.module.lq.sys.service.TRoutingService;
import com.object.module.lq.sys.entity.*;
import com.object.module.lq.sys.service.TRoleService;
import com.object.utils.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("TRoleServiceImpl")
public class TRoleServiceImpl extends ServiceImpl<TRoleDao, TRoleEntity> implements TRoleService {
    @Autowired
    private TRoutingService routingService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        QueryWrapper<TRoleEntity> wrapper = new QueryWrapper<>();
        String id = (String) params.get("id");
        String name = (String) params.get("name");
        if (StringUtils.isNotEmpty(id)) wrapper.eq("re_id", id);
        if (StringUtils.isNotEmpty(name)) wrapper.or().eq("re_name", name);
        IPage<TRoleEntity> page = this.page(
                new Query<TRoleEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    /**
     * 全部的角色查询
     *
     * @return
     */
    @Override
    public List<TRoutingEntity> purviewfindAll() {
        List<TRoutingEntity> list = routingService.list();
        //找出一级分类
        List<TRoutingEntity> collect = list.stream().filter((SortEntity ->
        {
            return SortEntity.getParentId() == 0;
        })).map(menu ->
        {
            menu.setChildren(getChider(menu, list));
            return menu;
        }).collect(Collectors.toList());
        return collect;
    }

    public List<TRoutingEntity> getChider(TRoutingEntity menu, List<TRoutingEntity> list) {
        List<TRoutingEntity> data = list.stream().filter(rout ->
        {
            return rout.getParentId() == menu.getId();
        }).map(rout ->
        {
            //找到子菜单
            rout.setChildren(getChider(rout, list));
            return rout;
        }).collect(Collectors.toList());
        return data;
    }

    @Autowired
    private TRolePermissionService tRolePermissionService;

    @Autowired
    private TRoleAuthorizationService tRoleAuthorizationService;

    @Override
    @LqTransaction
    public Q updateByIdRolePermission(TRoleEntity role) {
        //保存角色的路由
        boolean routePermissions = saveRoleRoutePermissions(role.getAuthority(), role.getReId());
        boolean saveTheRoute = theSpecificPermissionToSaveTheRoute(role.getPurviewS(), role.getReId());
        if (StringUtils.isNotEmpty(role.getReName())) {
            update(new LambdaUpdateWrapper<TRoleEntity>()
                    .set(TRoleEntity::getReName, role.getReName())
                    .eq(TRoleEntity::getReId, role.getReId()));
        }
        return routePermissions == saveTheRoute && routePermissions ? Q.ok() : Q.error();
    }

    /**
     * 保存路由的具体权限
     *
     * @param purview
     * @param reId
     * @return
     */
    private boolean theSpecificPermissionToSaveTheRoute(String[] purview, Integer reId) {
        //首先清除角色路由存在的数据
        QueryWrapper<TRoleAuthorizationEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("re_id", reId);
        tRoleAuthorizationService.remove(wrapper);
        List<TRoleAuthorizationEntity> permissionEntityList = RolePermissionUtil.ConvertPermissionToObjectSet(purview, reId);
        return tRoleAuthorizationService.saveBatch(permissionEntityList);
    }

    /**
     * 保存角色的路由
     *
     * @param authority
     * @param reId
     * @return
     */
    private boolean saveRoleRoutePermissions(String authority, Integer reId) {
        //首先清除角色存在的数据
        QueryWrapper<TRolePermissionEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("re_id", reId);
        tRolePermissionService.remove(wrapper);
        //数据进行封装
        String[] ids = authority.split(",");
        List<TRolePermissionEntity> rolePermissionEntities = new ArrayList<>();
        for (String id : ids) {
            TRolePermissionEntity permissionEntity = new TRolePermissionEntity();
            permissionEntity.setReId(reId);
            permissionEntity.setRtId(Integer.valueOf(id));
            rolePermissionEntities.add(permissionEntity);
        }
        return tRolePermissionService.saveBatch(rolePermissionEntities);
    }

    @Override
    public Q saveRolePermission(TRoleEntity role) {
        Check.check(role.getReName(), "角色名为必填！");
        boolean save = save(role);
        return save ? Q.ok() : Q.error();
    }

    @Override
    public Q getByIdPermissions(Integer reId) {
        TRoleEntity roleEntity = getById(reId);
        QueryWrapper<TRoleAuthorizationEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("re_id", reId);
        List<TRoleAuthorizationEntity> list = tRoleAuthorizationService.list(wrapper);
        List<Integer> rtIds = list.stream().map(i -> i.getRtId()).collect(Collectors.toList());
        Map<Integer, String> map = new HashMap<>();
        routingService.listByIds(rtIds).stream().forEach(i ->
        {
            map.put(i.getId(), i.getNickName());
        });
        list.forEach(i ->
        {
            i.setNickName(map.get(i.getRtId()));
        });
        return Q.ok().q("role", roleEntity).q("list", list);
    }

    @Override
    @LqTransaction
    public Q saveAuthonr(List<TRoleAuthorizationEntity> tRoleAuthorizationEntityList) {
        Integer reId = tRoleAuthorizationEntityList.get(0).getReId();
        //首先清除角色存在的数据
        QueryWrapper<TRolePermissionEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("re_id", reId);
        tRolePermissionService.remove(wrapper);
        QueryWrapper<TRoleAuthorizationEntity> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("re_id", reId);
        tRoleAuthorizationService.remove(wrapper1);

        tRoleAuthorizationService.saveBatch(tRoleAuthorizationEntityList);
        ArrayList<TRolePermissionEntity> rolePermissionEntities = new ArrayList<>();
        tRoleAuthorizationEntityList.forEach(i ->
        {
            TRolePermissionEntity permissionEntity = new TRolePermissionEntity();
            permissionEntity.setReId(reId);
            permissionEntity.setRtId(Integer.valueOf(i.getRtId()));
            rolePermissionEntities.add(permissionEntity);
        });
        tRolePermissionService.saveBatch(rolePermissionEntities);
        return Q.ok();
    }


    /**
     * 找出二级子路由
     */
    private List<TRoutingEntity> findOrderByRout(List<TRoutingEntity> list) {
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getParentId() == 0) {
                list.remove(i);
            }
        }
        return list;
    }
}
